package com.zusmart.base.network.nio;

import java.nio.channels.SocketChannel;

import com.zusmart.base.network.ChannelAdapter;
import com.zusmart.base.network.ChannelContext;
import com.zusmart.base.network.handler.support.DefaultRecognizeHandler;
import com.zusmart.base.network.message.MessageProtocol;
import com.zusmart.base.network.support.AbstractChannelContextManager;

public class NioChannelContextManager extends AbstractChannelContextManager {

	private final ChannelAdapter channelAdapter;
	private final NioChannelEventLoopGroup channelEventLoopGroup;

	public NioChannelContextManager(boolean serverSide, ChannelAdapter channelAdapter, NioChannelEventLoopGroup channelEventLoopGroup) {
		super(serverSide);
		this.channelAdapter = channelAdapter;
		this.channelEventLoopGroup = channelEventLoopGroup;
	}

	@Override
	public NioChannelContext createChannelContext(SocketChannel socketChannel) {
		return (NioChannelContext) super.createChannelContext(socketChannel);
	}

	@Override
	protected ChannelContext doCreateChannelContext(String contextCode, SocketChannel socketChannel) {
		MessageProtocol messageProtocol = this.channelAdapter.createMessageProtocol();
		NioChannelEventLoop channelEventLoop = this.channelEventLoopGroup.getEventLoop();
		NioChannelContext channelContext = new NioChannelContext(this.isServerSide(), contextCode, socketChannel, this, messageProtocol, channelEventLoop);
		this.channelAdapter.initChannelContextHandlerChain(channelContext.getChannelContextHandlerChain());
		channelContext.getChannelContextHandlerChain().addLast(DefaultRecognizeHandler.NAME, new DefaultRecognizeHandler(messageProtocol));
		return channelContext;
	}

	@Override
	protected void doStart() throws Exception {

	}

	@Override
	protected void doClose() throws Exception {
		for (ChannelContext context : this.getChannelContexts().values()) {
			context.close().waitComplete();
		}
	}

}